/*
 * Copyright (c) 2021 hpmicro
 *
 * SPDX-License-Identifier: BSD-3-Clause
 *
 */
#include <string.h>
#include "hpm_soc.h"
#include "hpm_clock_drv.h"
#include "hpm_mchtmr_drv.h"
//#include "boot_user.h"
#include "ota_api.h"
#include "tcp_echo.h"
#include "lwip/tcp.h"

#ifndef TIMER_CLK_NAME
#define TIMER_CLK_NAME clock_mchtmr0
#endif
#define DELAY_TIMER    3000 //3000ms

uint32_t mchtmr_freq_in_khz = 0;
static uint8_t recv_done = 0;

void isr_mchtmr(void)
{
    // printf("tiemr in!\n");
    if (recv_done == 0)
    {
        recv_done = 1;
    }
    else if (recv_done == 1)
    {
        recv_done = 0;
        ota_board_complete_reset();
    }
    mchtmr_delay(HPM_MCHTMR, mchtmr_freq_in_khz * DELAY_TIMER);
}
SDK_DECLARE_MCHTMR_ISR(isr_mchtmr)

static err_t tcpecho_recv(void* arg, struct tcp_pcb* tpcb, struct pbuf* p, err_t err)
{
    if (p != NULL) {
        // printf("recv len:%d\n", p->tot_len);
        recv_done = 0;
        ota_board_auto_write(p->payload, p->tot_len);
        tcp_recved(tpcb, p->tot_len);
        memset(p->payload, 0, p->tot_len);
        pbuf_free(p);
    } else if (err == ERR_OK) {
        return tcp_close(tpcb);
    }
    return ERR_OK;
}

static err_t tcpecho_accept(void *arg, struct tcp_pcb *newpcb, err_t err)
{
    tcp_recv(newpcb, tcpecho_recv);
    return ERR_OK;
}   

void tcp_echo_init(void)
{
    struct tcp_pcb* pcb = NULL;

    mchtmr_freq_in_khz = clock_get_frequency(TIMER_CLK_NAME) / 1000;
    mchtmr_delay(HPM_MCHTMR, mchtmr_freq_in_khz * DELAY_TIMER);
    enable_mchtmr_irq();

    pcb = tcp_new();
    tcp_bind(pcb, IP_ADDR_ANY, TCP_ECHO_PORT);
    pcb = tcp_listen(pcb);
    tcp_accept(pcb, tcpecho_accept);
}